package com.wux.labs.spring.springbucks.service.impl

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.wux.labs.spring.springbucks.entity.Coffee
import com.wux.labs.spring.springbucks.exception.RollbackException
import com.wux.labs.spring.springbucks.mapper.CoffeeMapper
import com.wux.labs.spring.springbucks.service.CoffeeService
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service("coffeeService")
@Transactional(rollbackFor = [RollbackException::class])
class CoffeeServiceImpl : ServiceImpl<CoffeeMapper, Coffee>(), CoffeeService {
    /**
     * 分页查询
     */
    override fun listByPage(pageNum: Long, pageSize: Long): MutableList<Coffee> {
        return baseMapper.listByPage(pageNum, pageSize)
    }

    /**
     * 创建记录
     */
    override fun create(coffee: Coffee): Boolean {
        var result = save(coffee)

        if (coffee.name == "rollback") {
            throw RollbackException("咖啡的名称是：'rollback'，所以回滚了！")
        }

        return result
    }

    /**
     * 修改记录
     */
    override fun update(coffee: Coffee): Int {
        var result = baseMapper.updateById(coffee)

        if (coffee.name == "rollback") {
            throw RollbackException("咖啡的名称是：'rollback'，所以回滚了！")
        }

        return result
    }

    /**
     * 删除记录
     */
    override fun delete(id: Long): Int {
        var result = baseMapper.deleteById(id)

        if (id in listOf<Long>(1, 2, 3, 4, 5)) {
            throw RollbackException("删除的记录ID在[1,2,3,4,5]中，所以回滚了！")
        }

        return result
    }

    /**
     * 无侵入式校验拦截
     */
    override fun interceptFilter(sql: String) {
        baseMapper.interceptFilter(sql)
    }
}